package Utils;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class IdCardVerification {

    public static final int[] W = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    public static final Map<Integer, String> VAR_MPA = new HashMap<>();

    static {
        VAR_MPA.put(0, "1");
        VAR_MPA.put(1, "0");
        VAR_MPA.put(2, "x");
        VAR_MPA.put(3, "9");
        VAR_MPA.put(4, "8");
        VAR_MPA.put(5, "7");
        VAR_MPA.put(6, "6");
        VAR_MPA.put(7, "5");
        VAR_MPA.put(8, "4");
        VAR_MPA.put(9, "3");
        VAR_MPA.put(10, "2");
    }

    public static boolean isVerification(String idNum) {
        boolean verification = false;
        if (idNum != null && (idNum.length() == 15 || idNum.length() == 18)) {
            int length = idNum.length();
            if (length == 15) {

            } else {
                verification = verification18(idNum);
            }
        }
        return verification;
    }

    private static boolean verification18(String idCard) {
        boolean verification18 = false;
        if (isRule18(idCard)) {
            verification18 = check18Rule(idCard);
        }
        return verification18;
    }

    private static boolean check18Rule(String idCard) {
        String numArea = idCard.substring(0, 17);
        String last = idCard.substring(17);
        int totalNum = 0;
        for (int i = 0; i < W.length; i++) {
            String num = String.valueOf(numArea.charAt(i));
            totalNum += Integer.parseInt(num) * W[i];
        }
        int preVer = totalNum % 11;
        return last.equalsIgnoreCase(VAR_MPA.get(preVer));
    }

    public static boolean isRule18(String idString) {
        String pattern = "[1-9][\\d]{16}[x|X|0-9]";
        return Pattern.matches(pattern, idString);
    }
}
